import request from '@/utils/request'

export function fetchList(query) {
  return request({
    url: '/generator/page',
    method: 'get',
    params: query
  })
}

export function fetchTableFieldList(query) {
  return request({
    url: '/generator/tableInfo',
    method: 'get',
    params: query
  })
}

export function batchGen(dataSource, tableNames) {
  return request({
    url: '/generator/batchGen',
    method: 'post',
    data: { dataSource: dataSource, tableNames: tableNames },
    responseType: 'arraybuffer'
  }).then((response) => { // 处理返回的文件流
    const blob = new Blob([response.data], { type: 'application/zip' })
    const filename = 'CodeGenerator.zip'
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = filename
    document.body.appendChild(link)
    link.click()
    window.setTimeout(function() {
      URL.revokeObjectURL(blob)
      document.body.removeChild(link)
    }, 0)
  })
}

export function handleDown(table) {
  return request({
    url: '/generator/code',
    method: 'post',
    data: table,
    responseType: 'arraybuffer'
  }).then((response) => { // 处理返回的文件流
    const blob = new Blob([response.data], { type: 'application/zip' })
    const filename = table.tableName + '.zip'
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = filename
    document.body.appendChild(link)
    link.click()
    window.setTimeout(function() {
      URL.revokeObjectURL(blob)
      document.body.removeChild(link)
    }, 0)
  })
}

export function genAppSkeleton(table) {
  return request({
    url: '/generator/gen-app-skeleton',
    method: 'post',
    data: table,
    responseType: 'arraybuffer'
  }).then((response) => { // 处理返回的文件流
    const blob = new Blob([response.data], { type: 'application/zip' })
    const filename = table.appName + '.zip'
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = filename
    document.body.appendChild(link)
    link.click()
    window.setTimeout(function() {
      URL.revokeObjectURL(blob)
      document.body.removeChild(link)
    }, 0)
  })
}

export function getForm(tableName, dsId) {
  return request({
    url: '/generator/info',
    params: { tableName: tableName, dataSource: dsId },
    method: 'get'
  })
}

export function postForm(formInfo, tableName, dsId) {
  return request({
    url: '/form/',
    method: 'post',
    data: Object.assign({ formInfo, tableName, dsId })
  })
}
